package com.candy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.candy.bean.LoginUser;
import com.candy.bean.User;
import com.candy.dao.MenuMapper;
import com.candy.dao.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    UserMapper userMapper;

    @Autowired
    MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//       查询用户信息
//        构建查询条件
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
//        使用等值查询，通过username的字段进行查询，传递的参数就是我们在登录时输入的用户名的信息
        queryWrapper.eq(User::getUserName,username);
        User userinfo=userMapper.selectOne(queryWrapper);
//        若该用户不存在
        if(Objects.isNull(userinfo)){
            throw new RuntimeException("用户名或密码错误");
        }
//        写好固定的权限
//        List<String> list = new ArrayList<>(Arrays.asList("test"));
//        从数据库中获取用户的权限信息
        List<String> permissionKeyList =  menuMapper.selectPermsByUserId(userinfo.getId());
        return new LoginUser(userinfo,permissionKeyList);
    }
}
